package com.hunantv.mglive.ui.live;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.LiveUrlModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.ui.live.liveinterface.OnVideoPlayCallBack;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.PlayMessageUploadMannager;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.media.IjkVideoView;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by qiuda on 16/3/25.
 */
public class StarLiveVideoFragment extends BaseFragment implements IMediaPlayer.OnCompletionListener, IMediaPlayer.OnPreparedListener, IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener {
    private static final int RETRY_COUNT = 10;
    private String mLid;
    private String mUid;
    private long mRetryCount;
    private boolean mIsplay;
    private String mPlayUrl;
    private View mLoadingView;
    private View mAnimView;
    private IjkVideoView mVideoView;
    private AnimationDrawable mAnimationDrawable;
    private OnVideoPlayCallBack mCallback;

    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            starVideo();
        }
    };


    public StarLiveVideoFragment() {
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_star_live_video, null);
        initView(view);
        if (!StringUtil.isNullorEmpty(mPlayUrl)) {
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    starVideo();
//                }
//            }, 300);
        }
        return view;
    }

    private void initView(View view) {
        mVideoView = (IjkVideoView) view.findViewById(R.id.ijk_star_live_video);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnInfoListener(this);

        mLoadingView = view.findViewById(R.id.rl_star_live_video_loading);
        mAnimView = view.findViewById(R.id.ll_star_live_video_anim);
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_star_live_video_loading);
        mAnimationDrawable = (AnimationDrawable) imageView.getDrawable();

        DisplayMetrics mts = getResources().getDisplayMetrics();
        mVideoView.setViewParams(mts.widthPixels, mts.heightPixels);
        startAnim();

    }

    private void startAnim() {
        mLoadingView.setVisibility(View.VISIBLE);
        mAnimView.setVisibility(View.VISIBLE);
        mLoadingView.setVisibility(View.VISIBLE);
        mAnimationDrawable.start();
    }

    private void loadData() {
        L.d(TAG, "—————————getPlayUrl");
        Map<String, String> requestBody = new FormEncodingBuilderEx().add(Constant.KEY_LID, mLid).add(Constant.KEY_UID, mUid).add(Constant.KEY_RATE, Constant.DE_RATE).build();
        post(BuildConfig.URL_LIVE_GET_URL, requestBody);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null && !StringUtil.isNullorEmpty(mPlayUrl)) {
            startAnim();
            starVideo();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            stopPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        IjkMediaPlayer.native_profileEnd();
    }

    /**
     * 停止播放
     */
    private void stopPlay() {
        if (mVideoView != null) {
            mVideoView.release(true);
            if(mIsplay) {
                mIsplay = false;
                mVideoView.stopPlayback();
                mVideoView.stopBackgroundPlay();

                Log.d(TAG, "stop");

                //停止视频卡顿信息上报
                PlayMessageUploadMannager.getInstance().stopUploadMessage();
                //完成上报
                PlayMessageUploadMannager.getInstance().doneUpMessage();
            }
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_LIVE_GET_URL.equals(url)) {
            L.d(TAG, "—————————result _serialization");
            return JSON.parseArray(resultModel.getData(), LiveUrlModel.class);
        }
        return super.asyncExecute(url, resultModel);

    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        super.onSucceed(url, resultModel);
        if (BuildConfig.URL_LIVE_GET_URL.equals(url)) {
            L.d(TAG, "—————————onsucceed -getPlayUrl");

            List<LiveUrlModel> mLiveUrls = (List<LiveUrlModel>) resultModel.getDataModel();
            mPlayUrl = StringUtil.getPlayUrl(mLiveUrls);

            //开始播放
            starVideo();

        }
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        if (BuildConfig.URL_LIVE_GET_URL.equals(url)) {
            if (mCallback != null) {
                L.d(TAG, "—————————error 播放地址为空");
                hideAnimView();
                mCallback.onError();

            }

        } else {
            Toast.makeText(getContext(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        Log.i(TAG, "onCompletion-->");
        L.d(TAG, "loadData video -onCompletion");
        mIsplay = false;
        if (!StringUtil.isNullorEmpty(mPlayUrl)) {
            mHandler.sendEmptyMessageDelayed(0, 1000);
        }
        hideAnimView();
        if (mCallback != null) {
            mCallback.onCompletion(mp);
        }

        //停止视频卡顿信息上报
        PlayMessageUploadMannager.getInstance().stopUploadMessage();
        //完成上报
        PlayMessageUploadMannager.getInstance().doneUpMessage();
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {

        //出错上报
        PlayMessageUploadMannager.getInstance().errUpMessage(what,extra);
        Log.i(TAG, "OnErr--->what--->" + what + "extra--->" + extra);
        if (!StringUtil.isNullorEmpty(mPlayUrl)) {//如果有设置拉流的地址，拉流失败，先提示重连，重试10次后，提示艺人不在线，后台则一直重试
            mHandler.sendEmptyMessageDelayed(0, 1000);
            mRetryCount++;

            if (mCallback != null) {
                if (mRetryCount < RETRY_COUNT) {
                    if (mIsplay) {
                        L.d(TAG, "—————————error 播放中断 重试10次以下");
                        mCallback.onVideoPuse();
                        Log.i(TAG, "OnErr_puse");
                    } else {
                        L.d(TAG, "—————————error 进入中断 重试10次以下");
                        hideAnimView();
                        mCallback.onError();
                    }
                } else {
                    L.d(TAG, "—————————error 已重试10");
                    hideAnimView();
                    mCallback.onError();
                }
            }
        } else {
            if (mCallback != null) {
                L.d(TAG, "—————————error 播放地址为空");
                hideAnimView();
                mCallback.onError();
            }
        }
        return true;
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {
        Log.i(TAG, "onPrepared-->");
        if (mCallback != null) {
            mCallback.onPrepared(mp);
        }
        mIsplay = true;
        mRetryCount = 0;
        mLoadingView.setVisibility(View.GONE);
    }


    public void setData(String lid, String uid) {
        mLid = lid;
        mUid = uid;
        loadData();
    }

    public void setData(String lid, String uid, String playUrl) {
        mLid = lid;
        mUid = uid;
        mPlayUrl = playUrl;
    }

    public void hideAnimView() {
        if (mAnimView != null) {
            mAnimView.setVisibility(View.GONE);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideAnimView();
                }
            }, 1000);
        }
    }

    public void setCallBack(OnVideoPlayCallBack call) {
        this.mCallback = call;
    }


    public void starVideo() {
        Map<String, String> params = new HashMap<>();
        params.put("auid", mUid);
        params.put("lvid", mLid);
        params.put("ap", "1");
        mVideoView.setVideoPath(mPlayUrl, params, IjkVideoView.VideoType.art);
        L.d(TAG, "—————————重试播放");
        mVideoView.start();

        Log.i(TAG, "start");


        //开启上报卡顿信息
        String host = StringUtil.getUrlHost(mPlayUrl);
        String path = "";
        if(!StringUtil.isNullorEmpty(host)){
            path = mPlayUrl.substring(host.length()+7);
        }
        try {
            path = URLEncoder.encode(path,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        PlayMessageUploadMannager.getInstance().startUploadMessage(host, path, "1");
    }

    @Override
    public synchronized boolean onInfo(IMediaPlayer mp, int what, int extra) {
        Log.i(TAG, "OnInfo-->"+what);
        switch (what) {
            case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (mCallback != null) {
                    mCallback.onVideoPuse();
                }

                Log.i(TAG, "OnPuse");

                PlayMessageUploadMannager.getInstance().addPuseCount();
                break;
            case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                if (mCallback != null) {
                    mCallback.onVideoResum();
                }
                PlayMessageUploadMannager.getInstance().doErrCount();
                break;
        }
        return false;
    }

}
